GraphQL (Hasura)系列,忘記介紹最一開始從前端連線到GraphQL (Hasura)一個重要的套件 - Apollo Client。
大致介紹一下這個Appolo Client 是什麼,他是一個 GraphQL + React 套件,除了支援React之外,也可以套用在其他的框架上。 這個套件可以讓我們用簡單的方式去跟GraphQL server溝通。
可參考以下連線方式:
import React from 'react';
import { render } from 'react-dom';
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  useQuery,
  gql
} from "@apollo/client";
const client = new ApolloClient({
  uri: 'https://48p1r2roz4.sse.codesandbox.io',
  cache: new InMemoryCache()
});
function App() {
  return (
    <div>
      <h2>My first Apollo app ?</h2>
    </div>
  );
}
render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('root'),
);
che: new InMemoryCache()
});
連線完畢後,搭配寫好的Graphql語法
const EXCHANGE_RATES = gql`
  query GetExchangeRates {
    rates(currency: "USD") {
      currency
      rate
    }
  }
`;
就可以使用類似像React Hook(比方說useState的方式)去跟Hasura取得資料
function ExchangeRates() {
  const { loading, error, data } = useQuery(EXCHANGE_RATES);
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;
  return data.rates.map(({ currency, rate }) => (
    <div key={currency}>
      <p>
        {currency}: {rate}
      </p>
    </div>
  ));
}
function App() {
  return (
    <div>
      <h2>My first Apollo app ?</h2>
      <ExchangeRates />
    </div>
  );
}